<template>
  <div id="cart">
    <!-- 导航栏 -->
    <van-nav-bar :title="$t('car.title')" :right-text="$t('car.delete')" @click-right="delCartData" />
    <!-- 已加入购物车的所有商品 -->
    <div class="cartWrapper">
      <!-- 购物车为空 -->
      <div class="emptyCart" v-if="!cartData.length">
        <img src="http://ddbuy.7-orange.cn/img/empty.5053d452.png" alt />
        <div class="title">{{$t('car.tip')}}</div>
        <router-link :to="{path:'/'}" class="goHome">{{$t('car.walk')}}</router-link>
      </div>
      <!-- 购物车有商品 -->
      <div class="contentWrapper" v-if="cartData.length">
        <van-checkbox
          v-for="(item,index) in cartData"
          :key="index"
          v-model="item.ischk"
          @change="changeIschk(item.id, index)"
          label-disabled
        >
          <van-card :title="item.product_name" :thumb="item.small_image" color="white">
            <div slot="price" style="font-size: 14px">{{ item.price | moneyFormat }}</div>
            <van-stepper
              slot="num"
              v-model="item.count"
              @change="changeNum(item.id, index)"
              integer
            />
          </van-card>
        </van-checkbox>
      </div>

      <van-submit-bar
        v-if="cartData.length"
        :price="totalPrice"
        :button-text="$t('order.settlement')"
        @submit="onSubmit"
      >
        <van-checkbox v-model="allChk">{{$t('car.all')}}</van-checkbox>
      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import { Dialog } from 'vant'
export default {
  data () {
    return {
      cart: JSON.parse(sessionStorage.getItem('cartGoods')),
      cartNum: 0,
      cartData: [] // 加入购物车商品
    }
  },
  methods: {
    getCartData () {
      // 查询购物车的商品
      this.$http.get(`/cart/${localStorage.getItem('userId')}`).then(res => {
        this.cartData = res.data.data
        res.data.data.forEach(v => {
          this.cartNum += v.count
        })

        sessionStorage.setItem('cartGoods', JSON.stringify(this.cartData))
      })
    },
    // 是否选中时触发的方法
    changeIschk (id, index) {
      this.$http.put(`/ischkCart/${id}`, this.cartData[index]).then(res => {})
    },
    // 数量改变时触发的方法
    changeNum (id, index) {
      this.$http.put(`/countCart/${id}`, this.cartData[index]).then(res => {})
    },
    // 删除商品
    delCartData () {
      Dialog.confirm({
        title: '温馨提示：',
        message: '确定要删除选中的商品吗？'
      })
        .then(() => {
          // on confirm
          let newList = this.cartData
          let listId = []
          // 遍历数组
          for (var i = 0; i < newList.length; i++) {
            if (newList[i].ischk === true || newList[i].ischk === 1) {
              // 存数组
              listId.push(newList[i].id)
            }
          }
          this.$http.delete(`/delCart?cid=${listId}`).then(res => {
            // 刷新数据
            this.getCartData()
          })
        })
        .catch(() => {
          // on cancel
        })
    },
    // 点击结算按钮
    onSubmit () {
      let newList = this.cartData
      let list = []
      // 遍历数组
      for (var i = 0; i < newList.length; i++) {
        if (newList[i].ischk === true || newList[i].ischk === 1) {
          // 存数组
          list.push(newList[i])
          // 跳转页面
          this.$router.push('/account')
        }
      }
      if (!list[0]) {
        // 必须要勾选一个
        this.$dialog.alert({
          message: '您至少要选择一样商品结算'
        })
      }
      // 保存到浏览器
      localStorage.setItem('shopList', JSON.stringify(list))
    }
  },

  created () {
    this.getCartData()
    this.allChk = false
  },
  computed: {
    // 总价
    totalPrice () {
      let sum = 0
      // 循环所有商品
      this.cartData.forEach(v => {
        // 如果勾选就把价格加到总价上
        if (v.ischk) {
          sum += v.price * v.count
        }
      })
      // 返回结果 (默认是分为单位，所有转化成元 *100)
      return sum * 100
    },
    // 全选
    allChk: {
      get () {
        // every方法，只要有一个错，那就是错，必须每一个对，才能返回对
        return this.cartData.every(item => item.ischk)
      },
      // 当点击全选按钮这个函数就被调用 参数：勾选之后的值
      set (newValue) {
        this.cartData.forEach(v => {
          // 判断商品不为null时修改勾选状态的值
          if (v !== null) {
            v.ischk = newValue
          }
        })
      }
    }
  },
  watch: {
    cartData: {
      deep: true,
      handler () {
        sessionStorage.setItem('cartGoods', JSON.stringify(this.cartData))
      }
    }
  }
}
</script>

<style lang="less">
#cart {
  width: 100%;
  min-height: 90vh;
  background-color: #f5f5f5;

  .van-checkbox__icon {
    margin-left: 0.625rem;
  }

  .van-submit-bar {
    bottom: 64px;
  }

  .cartWrapper {
    width: 100%;
    // min-height: 33.125rem;
    margin-bottom: 9.375rem;

    .emptyCart {
      display: flex;
      flex-direction: column;
      justify-content: center;

      img {
        padding-top: 2rem;
        width: 50%;
        height: 8rem;
        margin: 0 auto;
      }

      .title {
        text-align: center;
        padding: 0.5rem;
      }

      .goHome {
        margin-top: 2rem;
        color: #fff;
        background-color: #45c763;
        text-align: center;
        margin: 0 auto;
        padding: 0.5rem;
        width: 5rem;
        height: 1rem;
        line-height: 1rem;
        border-radius: 1rem;
      }
    }

    .contentWrapper {
      padding-top: 0.5rem;
      .van-checkbox {
        background-color: white;
        margin-bottom: 0.5rem;
      }

      .van-card {
        background-color: white;
      }

      .van-checkbox__label {
        width: 100%;
      }
    }
  }
}
</style>
